package utils;

import dto.FileDto;
import error.FileErrorCode;
import error.FileServiceException;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author xj
 * @since 1.0
 */
@Slf4j
public class FileUtil {


    public static StorageClient getStorageClient() {
        try {
            TrackerClient client = new TrackerClient();
            TrackerServer trackerServer = client.getTrackerServer();
            return new StorageClient(trackerServer);
        } catch (IOException e) {
            log.error("fdfs初始化失败IOException:{0}", e);
            throw new FileServiceException(FileErrorCode.FILE_SERVER_CONNTION_FAILE);
        }
    }

    public static String tokenUrl(FileDto file) {
        int lts = (int) (System.currentTimeMillis() / 1000);
        try {
            String url = file.getFileGroupPath() + "/" + file.getFileUrl();
            //初始化secret_key
            String token = ProtoCommon.getToken(file.getFileUrl()
                    , lts, ClientGlobal.getG_secret_key());
            return url + "?token=" + token + "&ts=" + lts;
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | MyException e) {
            log.error("file token is error:{0}", e);
        }
        return null;
    }
}
